﻿using System;
using System.Reflection;
using System.Web.Mvc;
using log4net;
using MSWeb.Models;
using MSWEB.Implementation;

namespace MSWeb.Controllers
{
    public class DaneFirmyController : Controller
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private readonly DataRepository _dataRepo;

        public DaneFirmyController()
        {
            _dataRepo = new DataRepository();
        }
        
        [Authorize]
        public ActionResult Index()
        {
            var df = _dataRepo.GetDaneFirmy();
            var result = new DaneFirmyModel
            {
                AdresFirmy = df.AdresFirmy,
                NazwaFirmy = df.NazwaFirmy,
                IDFirmy = df.IDFirmy
            };

            return View(result);
        }

        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(DaneFirmyModel daneFirmyModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _dataRepo.SaveOrUpdateCompanyData(daneFirmyModel);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                TempData["Error"] = "Wystapił błąd edycji.";
                Log.Error(ex.Message);
                Log.Error(ex.InnerException);
                return RedirectToAction("Index");
            }
            return null;
        }
    }
}